<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 17/3/2
 * Time: 16:53
 */

namespace Warehouse\Controller;

use Home\Controller\CommonController;
use Inbound\Service\PublicInfoService;
use Inbound\Service\PublicPlugService;
use Warehouse\Service\BaseInfoService;
use Warehouse\Service\PublicdataService;

class InventoryController extends CommonController
{
    //服务层对象
    public $inventory = null;

    //条件
    public $condition = array();

    public $storage   = null;
    //标志符
    public $flag;

    /**
     * PurchaseordersController constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->inventory    = D('Inventory', 'Service');
        $this->storage      = D('Storage', 'Model');
        $this->stockIn      = D('StockIn', 'Model');
        $this->shiftrecord  = D('Shiftrecord', 'Model');

        $this->export_tax_rebate = BaseInfoService::export_tax_rebate();
    }

    /**
     * 查询单个sku的库存信息
     */
    public function index()
    {
        if (!empty($_GET['sku']) && !empty($_GET['enterprise_dominant'] )) {
            $service         = $this->inventory;
            $this->condition = array(
                'sku'=>trim($_GET['sku']),
                'enterprise_dominant'=>trim($_GET['enterprise_dominant']),
                'site_id'=>trim($_GET['site_id'])
            );
            $stocks          = $service->getInventoriesInfo($this->condition);
            $taxstocks       = $service->getTaxInventoriesInfo($this->condition);

            $skuStatusAndPlace     = $service->getSkuStatusAndPlace($this->condition);
            $skuStorageInventories = $service->getStorageInventories($this->condition);


            $this->assign('stocks', $stocks);
            $this->assign('skuStatusAndPlace', $skuStatusAndPlace);
            $this->assign('skuStorageInventories', $skuStorageInventories);
            $this->assign('taxstocks', $taxstocks);
        }
        $this->assign('sites',PublicInfoService::get_site_array());
        $this->assign('enterprise_dominant',PublicInfoService::get_company_array());
        $this->display();
    }

    /**
     * 每月初更新期初库存
     * remark:不用这个,逻辑不适合
     */
    public function update_open_inventories_monthly()
    {
        $service = $this->inventory;

        $date    = date('Y-m-d');
        $openday = date('Y-m-01');
        if ($date == $openday) {
            $service->update_open_inventories();
        }
    }

    /**
     * 每月期初库存
     * khq 2017.4.28
     */
    public function qichu_inventories()
    {
        $service = $this->inventory;

        $service->qichu_inventories();
    }

    /**
     * 库存盘点初始界面
     * khq 2017.3.8
     */
    public function pandian()
    {
        $this->condition = $_GET;
        if($_GET['downcsv']){
            unset($_GET['downcsv']);
            $result = $this->inventory->inventories_data($_GET,false);                //详情导出
            $this->inventory->download_detail($result);
        }
        $result          = $this->inventory->inventories_data($_GET, true);
        $this->assign('result', $result);
        $this->assign('page', $this->inventory->page);
        $this->assign('count', $this->inventory->count);
        $this->assign('sites',PublicInfoService::get_site_array());
        $this->display();
    }

    /**
     * 库存盘点批量上传
     * khq 2017.3.9
     */
    public function upload()
    {
        if ($_POST) {
            $sheetData = PublicPlugService::parse_excel();                            //解析excel内容

            if (!PublicPlugService::$flag) {                                            //选择了上传文件,状态返回false
                if (count($sheetData) >= 2) {
                    $check_data = $this->inventory->check_upload_data($sheetData);    //检查导入的数据合法性
                    if (!$check_data['status']) {
                        $this->assign("result", $check_data['message']);
                        $this->display('Inventory/pandian');
                        exit;
                    }
                    $result = $this->inventory->upload_platform($sheetData);       //最后解析数据,验证,更新数据库
                    switch ($result['status']) {
                        case 401:
                            $this->assign("result", $result['message']);
                            break;
                        case 403:
                            $this->assign("result", "操作失败");
                            break;
                        case 200:
                            $this->assign("result", "操作成功");
                            break;
                    }
                } else {
                    $this->assign("result", "文件内容为空");
                }
            } else {
                $this->assign("result", "请选择上传文件");
            }
        }
        $this->display('Inventory/pandian');
    }

    /**
     *下载盘点库存的模板
     */
    public function down_template()
    {
        set_time_limit(0);
        vendor('PHPExcel.PHPExcel.IOFactory');
        $this->objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel     = new \PHPExcel();

        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet->setCellValue('A1', 'SKU');
        $objActSheet->setCellValue('B1', '单据下载时间');
        $objActSheet->setCellValue('C1', '品名');
        $objActSheet->setCellValue('D1', '储位');
        $objActSheet->setCellValue('E1', '盘点日期');
        $objActSheet->setCellValue('F1', '库存量');
        $objActSheet->setCellValue('G1', '实际盘点量');
        $objActSheet->setCellValue('H1', '公司主体');
        $objActSheet->setCellValue('I1', '站点');
        $objActSheet->setCellValue('J1', '是否出口退税 (出口退税/非出口退税)');
        $objPHPExcel->getActiveSheet()->setTitle('库存盘点');
        $objPHPExcel->setActiveSheetIndex(0);
        $day = date("Y-m-d");
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename="'.$day.'盘点库存模板.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 储位移位
     */
    public function move_storage()
    {
        if (IS_POST) {
            $storage_position = I('post.storage');
            $sku              = I('post.sku');

            //查询入库单数据
            $where = array();
            if ($storage_position) {
                $where['storage_position'] = $storage_position;
                $group = 'site_id, sku,export_tax_rebate,enterprise_dominant';
            } elseif ($sku) {
                $where['sku'] = $sku;
                $group = 'site_id, storage_position,export_tax_rebate,enterprise_dominant';
            }

            $field = 'site_id, storage_position, sku, enterprise_dominant, export_tax_rebate, sum(available_quantity) as available_quantity';
            $warehouseorders = $this->storage->get_move_warehouseorders($where, $field, $group);
            if (!$warehouseorders) {
                return $this->errorReturn('查询不到数据！');
            }

            //站点数据
            $sites    = PublicInfoService::get_site_array();
            //公司主体
            $companys = PublicInfoService::get_company_array();
            foreach ($warehouseorders as $key => &$value) {
                $value['site_name']         = $sites[$value['site_id']];
                $value['company_name']      = $companys[$value['enterprise_dominant']];
                $value['export_tax_rebate_text'] = $this->export_tax_rebate[$value['export_tax_rebate']];
            }

            return $this->successReturn($warehouseorders);
        } else {
            $this->display();
        }
    }

    /**
     * 站点调拨
     */
    public function move_inventory() {

        if (IS_POST) {
            $sku = I('post.sku');
            $where['sku'] = $sku;
            $where['available_quantity'] = array('gt',0);
            $result = $this->inventory->get_site_availiable($where);         //获取可用数量信息
            if(!$result) {
                return $this->errorReturn('查询不到数据！');
            }else{
                return $this->successReturn($result);
            }
        } else {
            $this->assign('sites',PublicInfoService::get_site_array());
            $this->display();
        }
    }

    /**
     * 确定站点调拨
     */
    public function do_move_site() {
        $site_arr = I('post.site');
        $available_quantity_arr = I('post.available_quantity');
        $storage_position_arr   = I('post.storage_position');
        $export_tax_rebate_arr  = I('post.export_tax_rebate');
        $enterprise_dominant_arr= I('post.enterprise_dominant');
        foreach (I('post.check') as $k=>$v){
            if($v==1) {
                if($available_quantity_arr[$k]<=0){
                    $this->errorReturn('调拨数量不能为0');
                }
                $site[]               = $site_arr[$k];
                $available_quantity[] = $available_quantity_arr[$k];
                $storage_position[]   = $storage_position_arr[$k];
                $export_tax_rebate[]  = $export_tax_rebate_arr[$k];
                $enterprise_dominant[]= $enterprise_dominant_arr[$k];
                $data = array(
                    'site' => $site,
                    'available_quantity' => $available_quantity,
                    'storage_position'   => $storage_position,
                    'export_tax_rebate'  => $export_tax_rebate,
                    'enterprise_dominant'=> $enterprise_dominant
                );
            }
        }
        $data['sku'] = strtoupper(trim(I('post.sku')));
        $data['site_id'] = I('post.site_id');

        $sites    = PublicInfoService::get_site_array();
        $to_site = $sites[$data['site_id']];
        if(in_array($to_site, $data['site'])){
            $this->errorReturn('不能调拨到自身站点中');
        }
        //(非)出口退税的站点只能移动到(非)出口退税的站点中
        $where['storage_position'] = array('in', array_merge($data['storage_position']));
        $storage = $this->storage->get_storage_lists($where, 'export_tax_rebate');
        $export_tax_rebate = array_unique(i_array_column($storage, 'export_tax_rebate'));
        if (count($data['export_tax_rebate'])>1 && count($export_tax_rebate) != 1) {
            $this->errorReturn('(非)出口退税的站点SKU只能移动到(非)出口退税的站点');
        }
        $flag   = $this->inventory->check_move_site_data($data);
        if($flag!==true) {
            $this->errorReturn($flag['message']);
            exit;
        }
        $result = $this->stockIn->site_move($data);
        if (!$result) {
            $this->errorReturn('移位失败！');
        }

        return $this->successReturn('移位成功！');
    }
    /**
     *  确定移位
     */
    public function do_move() {
        if (!$_POST) {
            $this->errorReturn('网络出错！请重试！');
        }
        //(非)出口退税的储位只能移动到(非)出口退税的储位
        $storageInfo = $this->storage->get_storage_by_where(array('storage_position' => $_POST['to_storage']));
        $export_tax_rebate = array($storageInfo['export_tax_rebate']);

        $checkData = $_POST['check'];
        foreach ($checkData as $key => $value) {
            $checkValue = json_decode($value, true);
            array_push($export_tax_rebate, $checkValue['export_tax_rebate']);
        }

        if (count(array_unique($export_tax_rebate)) != 1) {
            $this->errorReturn('(非)出口退税的储位SKU只能移动到(非)出口退税的储位');
        }
        $result = $this->stockIn->storage_move($_POST);
        if (!$result) {
            $this->errorReturn('移位失败！');
        }

        return $this->successReturn('移位成功！');
    }


    /*
     * 库存移位记录
     */
    public function shiftrecord() {
        $result = $this->shiftrecord->get_shiftrecord_data($_GET);

        $this->assign('result',$result);
        $this->assign('page',$this->Storage->page);
        $this->assign('count',$this->Storage->count);
        $this->display();
    }

    public function test() {
        $_array = array(
            'sku'=>'AM112700',
            'enterprise_dominant'=>1,
            'export_tax_rebate'=>0,
            'site_id'          => 107,
            'quantity'  => 1006
        );
        $mod = $this->inventory->auto_move_site($_array);
        print_r($mod);exit;
    }

    /**
     * sku实时库存
     */
    public function sku_real_inventory(){
        $condition = $_POST;
        if(isset($_POST['sku']) && $_POST['sku'] != ''){
            $condition['sku'] = $this->inventory->handle_sku(trim($_POST['sku']));
        }
        $data            = $this->inventory->getRealInventories($condition,true);

        $this->assign('sites',PublicInfoService::get_site_array());
        $this->assign('enterprise_dominant',PublicInfoService::get_company_array());
        $this->assign('page',$this->inventory->page);
        $this->assign('count',$this->inventory->count);
        $this->assign('data',$data);
        $this->display();
    }

    /**
     * sku实时库存下载
     */
    public function sku_real_inventory_download(){
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        $condition = $_POST;
        if(isset($_POST['sku']) && $_POST['sku'] != ''){
            $condition['sku'] = $this->inventory->handle_sku(trim($_POST['sku']));
        }
        $this->inventory->sku_real_inventory_download($condition);
    }
    /**
     * 描述: FBA库存数据监控
     * 作者: kelvin
     */
    public function fbaInventory() {
        $data = $this->inventory->fbaInventory($_GET);
        krsort($data);
        if($_GET['api']){
            $result = array();
            foreach($data as  $v){
                $result['dateDay'][] = substr($v['date'],5);
                $result['all_money'][] = intval($v['all_money']);
                $result['all_quantity'][] = intval($v['all_pcs']);
            }
            echo json_encode($result);die;
        }
        if($_GET['down']){
            $output = fopen('php://output', 'w') or die("can't open php://output");
            //告诉浏览器这个是一个csv文件
            $filename = "FBA库存监控列表明细".date('Ymd');
            header("Content-Type: application/csv");
            header("Content-Disposition: attachment; filename=$filename.csv");
            ob_end_clean();//关闭缓存
            //输出表头
            $table_head = array(
                '类型',
                'sku',
                '数量',
                '单价(元)'
            );
            $data = S('fbaInventoryDown');
            fputcsv($output, $table_head);
            foreach($data as $val){//$data_arr是数据集，二维数组
                fputcsv($output, array_values($val));
            }
            //关闭文件句柄
            fclose($output) or die("can't close php://output");
            exit;
        }
        $this->assign('data',$data);

        $this->display();
    }


    public function checkCode ()
    {
        $this->stockIn->checkCode();


    }
}